package com.darsystems.foghourz.server;

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.darsystems.foghourz.client.FBResponse;

public class FBResponseInternal extends FBResponse {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6421661047595108245L;
	private final Document _responseDoc;
	
	public FBResponseInternal(Document responseDoc)
	{
		_responseDoc = responseDoc;
		
		NodeList errorNodes = responseDoc.getElementsByTagName("error");
		
		if(errorNodes.getLength() > 0)
		{
			Element errNode = (Element)errorNodes.item(0);
			Integer errCode = Integer.parseInt(errNode.getAttribute("code"));
			setErrorInfo(errCode, ErrorMap.getText(errCode), errNode.getTextContent());
		}
	}
	
	public FBResponseInternal(Throwable e)
	{
		_responseDoc = null;
		setErrorInfo(ErrorMap.SERVICE_ERROR_CODE, ErrorMap.getText(ErrorMap.SERVICE_ERROR_CODE), e.getMessage());
	}
	
	private static String docToResponseString(Document doc) throws Error, Exception
	{
		doc.setXmlStandalone(true);
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		//transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		//initialize StreamResult with File object to save to file
		StreamResult result = new StreamResult(new StringWriter());
		DOMSource source = new DOMSource(doc);
		transformer.transform(source, result);
		return result.getWriter().toString();
	}
	
	public FBResponse getBaseResponse()
	{
		try {
			Integer errCode = getErrorCode();
			if(errCode != 0)
			{
				return new FBResponse(this.getErrorCode(), this.getErrorText(), this.getErrorDetails());
			}
			else
			{
				return new FBResponse(docToResponseString(_responseDoc));
			}
		} catch (Throwable e) {
			return makeServiceErrorResponse(e);
		}
	}
	
	public Document getResponseDoc()
	{
		return _responseDoc;
	}
	
	private static FBResponse makeServiceErrorResponse(Throwable e)
	{
		return new FBResponse(ErrorMap.SERVICE_ERROR_CODE, ErrorMap.getText(ErrorMap.SERVICE_ERROR_CODE), e.getMessage());
	}
	
	
}
